package com.jason.android.core.builder;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * Intent 跳转的基本方法工具类
 * 
 * @author zhoushengtao
 */
public class ActivityBuilder {
	private Class<?> targetClass;
	private int enId = 0, outId = 0;
	private Context context;
	private Map<String, String> paramMap;
	private int flag = Intent.FLAG_ACTIVITY_CLEAR_TOP;
	private int requestCode = -1;

	public ActivityBuilder(Context c) {
		context = c;
	}

	public ActivityBuilder setTargetClass(Class<?> c) {
		targetClass = c;
		return this;
	}

	public ActivityBuilder setAnimtion(int enter, int outer) {
		enId = enter;
		outId = outer;
		return this;
	}

	public ActivityBuilder setParam(Map<String, String> map) {
		paramMap = map;
		return this;
	}

	public ActivityBuilder setFlag(int f) {
		flag = f;
		return this;
	}

	public ActivityBuilder addParam(String key, String value) {
		if (paramMap == null)
			paramMap = new HashMap<String, String>();
		paramMap.put(key, value);
		return this;
	}

	public void start() {
		buildActivity();
	}

	public void startForResult(int r) {
		requestCode = r;
		buildActivity();
	}

	private void buildActivity() {
		Intent intent = new Intent(context, targetClass);
		if (null != paramMap) {
			Set<String> set = paramMap.keySet();
			for (Iterator<String> iterator = set.iterator(); iterator.hasNext();) {
				String key = iterator.next();
				intent.putExtra(key, paramMap.get(key));
			}
		}
		if (flag != 0)
			intent.addFlags(flag);

		if (requestCode > 0)
			((Activity) context).startActivityForResult(intent, requestCode);
		else
			context.startActivity(intent);

		if (context instanceof Activity)
			if (enId != -1 && outId != -1)
				((Activity) context).overridePendingTransition(enId, outId);
	}
}
